<template>
  <div class="app-container">
    <div class="search-area" v-show="showSearch">
      <el-form
        :model="queryParams"
        @submit.native.prevent
        ref="queryForm"
        size="small"
        :inline="true"
        class="clearfix"
        label-width="auto"
      >
        <el-form-item label="合同名称" prop="contractName">
          <el-input
            v-model="queryParams.contractName"
            placeholder="请输入合同名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNumber">
          <el-input
            v-model="queryParams.contractNumber"
            placeholder="请输入合同编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="合同分类" prop="contractCategoryList">
          <el-select
            v-model="queryParams.contractCategoryList"
            multiple
            collapse-tags
            placeholder="请选择合同分类"
            clearable
          >
            <el-option
              v-for="dict in dict.type.contract_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="合同进度" prop="contractProgressList">
          <el-select
            v-model="queryParams.contractProgressList"
            multiple
            collapse-tags
            placeholder="请选择合同进度"
            clearable
          >
            <el-option
              v-for="dict in dict.type.contract_progress"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectId">
          <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable />
          <!-- <el-select
            v-model="queryParams.projectId"
            placeholder="输入关键字可选择更多项目"
            clearable
            :remote-method="getProjectList"
            v-loading="projectLoading"
            filterable
            remote
            reserve-keyword
            :clear="
              () => {
                getProjectList('')
              }
            "
          >
            <el-option v-for="item in projectList" :key="item.id" :label="item.projectName" :value="item.id" />
          </el-select> -->
        </el-form-item>
        <el-form-item label="项目类型" prop="projectTypeList">
          <el-select
            v-model="queryParams.projectTypeList"
            multiple
            collapse-tags
            placeholder="请选择项目类型"
            clearable
          >
            <el-option
              v-for="dict in dict.type.project_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="中标日期" prop="winBiddingDateList">
          <el-date-picker
            v-model="queryParams.winBiddingDateList"
            style="width: 220px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>


        <el-form-item label="合同签订日期" prop="timeList">
          <el-date-picker
            v-model="queryParams.timeList"
            style="width: 220px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="main-content">
      <el-row :gutter="10" class="mb24">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['biz:contract:information:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-document-copy"
            size="mini"
            @click="handleCopy"
            :disabled="multiple"
            v-hasPermi="['biz:contract:information:add']"
            >复制</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['biz:contract:information:remove']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-setting"
            size="mini"
            @click="handleSetType()"
            v-hasPermi="['biz:contract:information:getContractNumber']"
            >合同编号设置</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button plain size="mini" @click="downloadTemplate()" v-hasPermi="['biz:contract:information:import']"
            >下载导入模板</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-plus"
            size="mini"
            @click="importData()"
            v-hasPermi="['biz:contract:information:import']"
            >导入</el-button
          >
          <input
            type="file"
            @change="onFileChange"
            ref="uploadFileInput"
            enctype="multipart/form-data"
            style="display: none"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          />
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      </el-row>
      <el-table
        v-loading="loading"
        :data="informationList"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
        :default-sort = "{ order: 'descending'}"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="合同名称"
          align="center"
          width="240"
          prop="contractName"
          v-if="columns.contractName.visible" fixed
        />
        <el-table-column label="合同编号" align="center" prop="contractNumber" v-if="columns.contractNumber.visible"  width="180"/>
        <el-table-column label="合同分类" prop="categoryName" align="center" v-if="columns.contractCategory.visible"  width="180">
        </el-table-column>
        <el-table-column label="供应商/客户" align="center" v-if="columns.supplierId.visible"    width="180"
        >
          <template slot-scope="scope">
            {{ scope.row.contractCategory === 1 ? scope.row.customerName : scope.row.supplierName }}
          </template>
        </el-table-column>
        <el-table-column label="项目" align="center" prop="projectName" v-if="columns.projectId.visible" width="180" />
        <el-table-column label="项目类型" align="center" v-if="columns.projectType.visible"  width="180" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.project_type" :value="scope.row.projectType" />
          </template>
        </el-table-column>
        <el-table-column
          label="合同金额(元)"
          align="center"
          prop="contractAmount"
          v-if="columns.contractAmount.visible"  width="180"
        >
          <template slot-scope="scope">
            {{ scope.row.contractAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          label="合同负责主体"
          align="center"
          prop="contractResponsibleParty"
          v-if="columns.contractResponsibleParty.visible"  width="180"
        />
        <el-table-column label="合同进度" align="center" v-if="columns.contractProgress.visible">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.contract_progress" :value="scope.row.contractProgress" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="审核状态" align="center" v-if="columns.status.visible">
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.contract_status" :value="scope.row.status" />
                  </template>
                </el-table-column>-->
        <el-table-column
          label="合同签订时间"
          align="center"
          sortable="custom"
          prop="contractSignDate"
          v-if="columns.contractSignDate.visible"  width="180"
        />

        <el-table-column
          label="合同负责人"
          align="center"
          prop="contractManager"
          v-if="columns.contractManager.visible"  width="180"
        />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180"  fixed="right">
          <template slot-scope="scope">
            <!-- <el-button
              size="mini"
              type="text"
              icon="el-icon-user"
              v-if="[0, 3].indexOf(scope.row.status) > -1"
              v-hasPermi="['biz:approval:add']"
              v-loading="auditLoading"
              @click="handleAudit(scope.row)"
              >提交审核</el-button
            > -->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-tickets"
              @click="handleUpdate(scope.row, true)"
              v-hasPermi="['biz:contract:information:getInfo']"
              >查看</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['biz:contract:information:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['biz:contract:information:remove']"
              >删除</el-button
            ><!--
            <el-button
              v-if="scope.row.status > 0"
              size="mini"
              type="text"
              icon="el-icon-s-check"
              v-hasPermi="['biz:contract:information:approvalProcess']"
              v-loading="auditLoading"
              @click="handleAuditProgress(scope.row.contractId)"
              >审核进度</el-button
            >-->
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <contract-details :show="open" :disabled="disabled" @cancel="cancel" @refresh="getList" :id="dataSource.id || ''" />
    <audit-progress ref="auditProgress" />
  </div>
</template>

<script>
import { listInformation, delInformation, approval, contractInformationCopy, importContract } from '@/api/biz/contract'
import { listProject } from '@/api/biz/project'
import ContractDetails from './components/ContractDetails.vue'
import AuditProgress from './components/AuditProgress.vue'
import { listType } from '@/api/system/dict/type'
export default {
  name: 'Information',
  components: {
    ContractDetails,
    AuditProgress,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同信息表格数据
      informationList: [],
      // 弹出层标题
      title: '',
      // 是否禁止表单填写
      disabled: false,
      // 是否显示弹出层
      open: false,
      dataSource: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractName: null,
        contractNumber: null,
        timeList: [],
        winBiddingDateList: [],
        contractProgressList: null,
        contractCategoryList: null,
        projectTypeList: null,
        projectName: null,
        customerName: '',
        sortList: [],
      },
      // 列信息
      columns: {
        contractName: { label: '合同名称', visible: true },
        contractNumber: { label: '合同编号', visible: true },
        contractCategory: { label: '合同分类', visible: true },
        supplierId: { label: '供应商id', visible: true },
        projectId: { label: '项目id', visible: true },
        projectType: { label: '项目类型', visible: true },
        contractAmount: { label: '合同金额', visible: true },
        contractResponsibleParty: { label: '合同负责主体', visible: true },
        contractProgress: { label: '合同进度', visible: true },
        // status: { label: '审核状态', visible: true },
        contractSignDate: { label: '合同签订时间', visible: true },
        contractManager: { label: '合同负责人', visible: true },
      },
      projectList: [],
      projectLoading: false,
      auditLoading: false,
      copyLoading: false,
    }
  },
  dicts: ['contract_progress', 'contract_category', 'contract_status', 'project_type'],
  created() {
    const { supplierId = null, contractCategory = null, customerId = null } = this.$route.query ? this.$route.query : {}
    this.queryParams.supplierId = supplierId
    this.queryParams.contractCategory = contractCategory
    this.queryParams.customerId = customerId
    this.getList()
  },
  methods: {
    sortChange({ order }) {
      console.log("排序：", order)
      const type = {
        ascending: 'contract_sign_date ASC',
        descending: 'contract_sign_date DESC',
      }
      this.$set(this.queryParams, 'sortList', type[order]?[type[order]]:[])
      this.$nextTick(()=>{
        this.getList()
      })
    },
    handleCopy() {
      const contractIds = this.ids
      if (contractIds.length > 1) {
        this.$modal.msgError('不支持复制多个')
        return
      }
      this.copyLoading = true
      contractInformationCopy(contractIds.join(','))
        .then(() => {
          this.copyLoading = false
          this.$modal.msgSuccess('复制成功')
          this.resetQuery()
        })
        .catch(() => {
          this.copyLoading = false
          this.$modal.msgError('复制失败')
        })
    },
    getProjectList(query = '') {
      this.projectLoading = true
      listProject({
        projectName: query,
      })
        .then((response) => {
          this.projectList = response.rows
          this.projectLoading = false
        })
        .catch(() => {
          this.projectLoading = false
        })
    },
    /** 查询合同信息列表 */
    getList() {
      this.loading = true
      listInformation({ ...this.queryParams })
        .then((response) => {
          this.informationList = response.rows
          this.total = response.total
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        contractId: null,
        contractName: null,
        contractNumber: null,
        contractCategory: null,
        supplierId: null,
        projectId: null,
        contractAmount: null,
        contractResponsibleParty: null,
        contractProgress: null,
        contractSignDate: null,
        contractManager: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        delFlag: null,
        remark: null,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.supplierId = null
      this.queryParams.customerId = null
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.supplierId = null
      this.queryParams.contractCategoryList = null
      this.queryParams.customerId = null
      this.queryParams.contractName = null
      this.queryParams.contractNumber = null
      this.queryParams.contractProgressList = null
      this.queryParams.projectName = null
      this.queryParams.timeList = []
      this.queryParams.winBiddingDateList = []
      this.queryParams.sortList = []
      this.queryParams = { ...this.queryParams }
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.contractId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.dataSource = {}
      this.disabled = false
      this.open = true
    },
    /** 修改按钮操作 */
    handleUpdate(row, disabled = false) {
      this.reset()
      const contractId = row.contractId || this.ids
      this.dataSource = {
        id: contractId,
      }
      this.open = true
      this.disabled = disabled
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const contractIds = row.contractId || this.ids
      this.$modal
        .confirm('是否确认删除合同信息编号为"' + contractIds + '"的数据项？')
        .then(function () {
          return delInformation(contractIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'biz/information/export',
        {
          ...this.queryParams,
        },
        `information_${new Date().getTime()}.xlsx`
      )
    },
    handleAudit(data) {
      this.$confirm('是否提交审核', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.auditLoading = true
        approval({
          approvalFormType: 'CONTRACT_APPROVAL',
          id: data.contractId,
        })
          .then(() => {
            this.getList()
            this.auditLoading = false
            this.$message({
              type: 'success',
              message: '操作成功',
            })
          })
          .catch(() => {
            this.auditLoading = false
          })
      })
    },
    handleAuditProgress(id) {
      this.$refs.auditProgress.init(id)
    },
    handleSetType() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      let url = window.location.origin
      listType({ dictType: 'contract_number' }).then((response) => {
        const [item = {}] = response.rows
        loading.close()
        if (item.dictId) {
          window.open(`${url}/system/dict-data/index/${item.dictId}`)
        } else {
          this.$message.error('请先设置字典：contract_number')
        }
      })
    },
    onFileChange() {
      const formData = new FormData()
      formData.append('file', this.$refs.uploadFileInput.files[0])
      this.loading = true
      importContract(formData)
        .then((response) => {
          this.loading = false
          this.$modal.msgSuccess('导入成功')
          // 清除文件内容，避免下次不生效
          this.$refs.uploadFileInput.value = ''
          this.resetQuery()
        })
        .catch((err) => {
          this.loading = false
          // 清除文件内容，避免下次不生效
          this.$refs.uploadFileInput.value = ''
        })
    },
    importData() {
      this.$refs.uploadFileInput.click()
    },
    downloadTemplate() {
      this.loading = true
      // 使用相对路径
      const fileUrl = '/contractTemplate.xlsx'
      // 创建一个隐藏的a标签
      const link = document.createElement('a')
      link.href = fileUrl
      link.download = '合同模板.xlsx' // 设置下载文件名
      // 将a标签添加到DOM并触发点击事件
      document.body.appendChild(link)
      link.click()
      // 移除a标签
      document.body.removeChild(link)
      this.loading = false
      this.$modal.msgSuccess('下载成功')
    },
  },
}
</script>
<style scoped lang="scss">
.el-date-editor,
.el-select {
  width: 100%;
}
</style>
